import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.customization.huangwm.utils.HttpRequest;
import com.customization.huangwm.utils.LogTool;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.GCONST;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Huangwm
 * @Date 2022-05-05
 * @Version 1.0
 * @Description TODO
 **/
public class DeBug {
    private static LogTool logTool = new LogTool("/log/huangwm/model/action/ImportAssetBeforeAcion", false);

    public static void main(String[] args) {
        String rootPath = "E:\\WEAVER9\\ecology\\";
        GCONST.setRootPath(rootPath);
        GCONST.setServerName("ecology");
        try {
            Workbook xssfWorkbook1 = new XSSFWorkbook(new FileInputStream("D:\\WeChat\\WeChat Files\\hwm19970225\\FileStorage\\File\\2023-02\\LAB_物料.xlsx"));
            //创建工作簿
            //Workbook xssfWorkbook = new XSSFWorkbook(new FileInputStream("D:\\WeChat\\WeChat Files\\hwm19970225\\FileStorage\\File\\2023-02\\LAB_物料.xlsx"));
            //读取第一个工作表
            Sheet sheet = xssfWorkbook1.getSheetAt(0);
            //获取最后一行的num，即总行数。此处从0开始计数
            int maxRow = sheet.getLastRowNum();
            List<List<String>> Excel_datas = new ArrayList<>();
            List<String> codes = new ArrayList<>();
            BaseBean baseBean = new BaseBean();
            String eop_reqToken = baseBean.getPropValue("SW003", "eop_reqToken");
            if (eop_reqToken.isEmpty()) {
                System.err.println("獲取SW003.peoperties中的eop_reqToken爲空");
            }
            if (!(sheet.getRow(0).getCell(1) + "").equals("物料編碼")) {
                System.err.println("Excel模板格式錯誤,第二列應為物料編碼,現為[" + sheet.getRow(0).getCell(1) + "]");
            }
            try {
                for (int row = 1; row <= maxRow; row++) {
                    List<String> data = new ArrayList<>();
                    //获取最后单元格num，即总单元格数 ***注意：此处从1开始计数***
                    int maxCel = sheet.getRow(row).getLastCellNum();
                    System.err.println("--------第" + row + "行的数据如下--------");
                    for (int cel = 1; cel < 12; cel++) {
                        if (cel == 1) {
                            sheet.getRow(row).getCell(cel).setCellType(CellType.STRING);
                            if (!isBlank(sheet.getRow(row).getCell(cel) + "").isEmpty()) {
                                codes.add(sheet.getRow(row).getCell(cel).getStringCellValue() + "");
                            } else {
                                System.err.println("第" + row + "行物料編碼存在空值");
                            }
                            data.add(isBlank(sheet.getRow(row).getCell(cel).getStringCellValue() + ""));
                        }
                        else if(cel == 2){
                            sheet.getRow(row).getCell(cel).setCellType(CellType.STRING);
                            data.add(
                                    isBlank(sheet.getRow(row).getCell(cel).getStringCellValue()).replace(String.valueOf((char)160)," ")
                            );
                        } else{
                            data.add(isBlank(sheet.getRow(row).getCell(cel) + ""));
                        }

                    }
                    System.err.println(JSON.toJSONString(data));
                    Excel_datas.add(data);

                }
                System.err.println(codes.size());
            }catch (Exception e){
                e.printStackTrace();
                System.err.println(e.getLocalizedMessage());
            }

            if (codes.size() > 0 && Excel_datas.size() > 0) {
//                String check = check(codes);
//                if(!check.isEmpty()){
//                    System.err.println(check);
//                }
                try {
                    //分解数据传入用友
                    Map<String, Object> reqData = new HashMap<>();
                    List<Map<String, Object>> datas = new ArrayList<>();//reqData中的data
                    for (List<String> value : Excel_datas) {
                        Map<String, Object> data = new HashMap<>();
                        Map<String, String> invbas = new HashMap<>();
                        Map<String, String> invman = new HashMap<>();
                        String assetCode = value.get(0);//物料編碼
                        invbas.put("id", assetCode);
                        invbas.put("invcode ", assetCode);
                        String assetName = value.get(1);//物料名稱
                        invbas.put("invname ", replaceStr(assetName));
                        invbas.put("forinvname ", replaceStr(assetName));
                        invbas.put("invshortname ", replaceStr(assetName));
                        String assetDic = value.get(2);//物料描述
                        invman.put("memo", replaceStr(assetDic));//將物料描述當作備注
                        String unit = value.get(3);//單位
                        invbas.put("pk_measdoc ", unit);
                        String managerDep = value.get(4);//管理部門
                        String isAsset = value.get(5);//是否資產
                        invbas.put("asset", (isAsset.equals("Y") || isAsset.equals("是")) ? "Y" : "N");
                        String model = value.get(6);//型號
                        invbas.put("invtype ", replaceStr(model));
                        String assetType = value.get(7);//物料種類
                        invbas.put("pk_invcl", assetType);
//                        Double totalquantity = Double.parseDouble(value.get(8));//总入库数量
//                        Double usedQuantity = Double.parseDouble(value.get(9));//已領用數量
//                        Double InventoryQuantity = Double.parseDouble(value.get(10));//庫存數量
//

                        //invbas其他參數
                        invbas.put("setpartsflag", "N");
                        invbas.put("invspec", "");
                        invbas.put("pk_corp", "MW");
                        invbas.put("discountflag", "N");
                        invbas.put("setpartsflag", "N");
                        invbas.put("assistunit", "N");
                        invbas.put("ismngstockbygrswt", "N");
                        invbas.put("autobalancemeas", "Y");
                        invbas.put("isstorebyconvert", "N");
                        invbas.put("isretail", "N");
                        invbas.put("taxitems", "9003");
                        //invman其他參數
                        invman.put("sellproxyflag", "N");
                        invman.put("planprice", "0");
                        invman.put("costprice", "0");
                        invman.put("refsaleprice", "0");
                        invman.put("consumesettleflag", "N");
                        invman.put("qualitymanflag", "N");
                        invman.put("qualityperiodunit", "2");
                        invman.put("qualitydaynum", "0");
                        invman.put("serialmanaflag", "N");
                        invman.put("wholemanaflag", "N");
                        invman.put("sealflag", "N");//是否封存
                        invman.put("accflag", "N");
                        invman.put("outtrackin", "N");
                        invman.put("negallowed", "N");
                        invman.put("iscanpurchased", "Y");
                        invman.put("iscansold", "N");
                        invman.put("issalable", "Y");
                        invman.put("isnoconallowed", "Y");

                        data.put("invbas", invbas);
                        data.put("invman", invman);
                        datas.add(data);
                    }
                    reqData.put("data", datas);
                    HttpRequest http = new HttpRequest();
                    JSONObject params = new JSONObject();
                    params.put("reqNb", http.getTimestamp());
                    params.put("reqLang", "zh");
                    params.put("reqToken", eop_reqToken);
                    params.put("reqData", reqData);
                    System.err.println("---傳入用友參數如下---");
                    System.err.println(JSON.toJSONString(params));
                    try{
                        JSONObject json = http.CallApiPost("https://testeop.macaowater.com/eop/eapToUfida/bsinvman", JSONObject.toJSONString(""));
                        System.err.println("---傳入用友結果如下---");
                        System.err.println(JSON.toJSONString(json));
                    }catch (Exception e){
                        e.printStackTrace();
                        System.err.println("---傳入用友失败" +e.getLocalizedMessage());
                    }

                    String times = http.getTimestamp();
                    //寫入用友期初庫存
//                    JSONObject params_Bill = new JSONObject();
//                    params_Bill.put("reqNb", times);
//                    params_Bill.put("reqLang", "zh");
//                    params_Bill.put("reqToken", eop_reqToken);
//                    Map<String, Object> reqData_Bill = new HashMap<>();
//                    List<Map<String, Object>> bill = new ArrayList<>();//reqData中的bill
//                    Map<String, Object> bill_data = new HashMap<>();
//                    //billHead内容
//                    Map<String, Object> billHead = new HashMap<>();
//                    billHead.put("id",times);
//                    billHead.put("cbilltypecode","4D");
//                    billHead.put("dbilldate","2022-07-19");
//                    billHead.put("pk_corp","MW");
//                    billHead.put("vbillcode","");
//                    billHead.put("cdispatcherid","21");
//                    billHead.put("cdeptid","depid");
//                    billHead.put("pk_calbody","MW");
//                    billHead.put("cwarehouseid","01");
//                    billHead.put("coperatorid","coperatorid");
//                    billHead.put("fbillflag","2");
//                    billHead.put("vnote","期初");
//                    //添加billhead内容
//                    bill_data.put("billHead",billHead);
//
//                    List<Map<String, Object>> billBody = new ArrayList<>();
//                    for (List<String> value : Excel_datas) {
//                        //如果導入數量大於0才插入
//                        String assetCode = value.get(0);//物料編碼
//                        String assetName = value.get(1);//物料名稱
//                        String assetDescribe = value.get(2);//物料描述
//                        String unit = value.get(3);//單位
//                        String managerDep = value.get(4);//管理部門
//                        String isAsset = value.get(5);//是否資產
//                        String assetModel = value.get(6);//型號
//                        String assetType = value.get(7);//EAP物料種類
//                        //System.err.println(value.get(8)+"-"+value.get(9)+"-"+value.get(10));
//                        Double totalquantity = Double.parseDouble(value.get(8));//总入库数量
//                        Double usedQuantity = Double.parseDouble(value.get(9));//已領用數量
//                        Double InventoryQuantity = Double.parseDouble(value.get(10));//庫存數量
//                        if((totalquantity-usedQuantity)>0){
//                            Map<String, Object> billBody_data = new HashMap<>();
//                            billBody_data.put("cinventoryid",assetCode);
//                            billBody_data.put("dbizdate","2022-07-19");
//                            billBody_data.put("noutnum",String.format("%.2f",(totalquantity-usedQuantity)));
//                            billBody_data.put("nprice","0");
//                            billBody_data.put("nmny","0");
//                            //添加body内容
//                            billBody.add(billBody_data);
//                        }
//
//                    }
//                    bill_data.put("billBody",billBody);
//                    bill.add(bill_data);
//                    reqData_Bill.put("bill",bill);
//                    params_Bill.put("reqData",reqData_Bill);
//
//                    System.err.println("---期初入庫傳入用友參數如下---");
//                    System.err.println(JSON.toJSONString(params_Bill));
                } catch (Exception e) {
                    e.printStackTrace();
                    System.err.println("扩展接口获取分解數據傳入用友出現異常 " + e.toString());
                }
            } else {
                System.err.println("扩展接口获取excel数据为空1");
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("扩展接口获取excel数据为空2");
        }
    }

    public static String isBlank(String str) {
        if (str.isEmpty() || str.equals("null")) return "";
        return str.trim();
    }

    public static String replaceStr(String str){
        String s =  "<![CDATA["+str+"]]>";
        return s;
    }
    /**
     * 检查本次导入的数据中是否存在相同的itemcode
     * @param codes
     * @return
     */
    public static String check(List<String> codes) {
        if (codes.size() <= 0) return "物料编码集合为空";
        RecordSet rs = new RecordSet();
        int i = 1;
        for (String code : codes) {
            rs.execute("select id from uf_003_AssteInfo where assetCode='" + code + "'");
            if (rs.next()) {
                return "第" + i + "行物料编码已存在";
            }
        }
        return "";
    }

    /**
     * 獲取物料單位code
     *
     * @param rs
     * @param name
     * @return
     */
    public static String getUnitCode(RecordSet rs, String name) {
        if (name.isEmpty()) return "NULL";
        String code = "NULL";
        rs.execute("select unit_code from uf_003_unit where unit_name='" + name + "'");
        if (rs.next()) {
            code = rs.getString("unit_code");
        }
        return code;
    }

    /**
     * 獲取物料種類code
     *
     * @param rs
     * @param name
     * @return
     */
    public static String getTypeCode(RecordSet rs, String name) {
        if (name.isEmpty()) return "NULL";
        String code = "NULL";
        rs.execute("select type_code from uf_003_Type where type_name='" + name + "'");
        if (rs.next()) {
            code = rs.getString("type_code");
        }
        return code;
    }


}
